import { showToast } from "./common";

const strategies = {
  checkEmpty: function (val, msg) {
    if (!val) {
      showToast({ msg });
    }
    return val ? true : false;
  },
  checkPhoneNumber: function (val, msg) {
    if (/^1\d{10}/.test(val)) {
      return true;
    } else {
      showToast({ msg });
      return false;
    }
  },
  checkIntNotZero: function (val, msg) {
    if (val > 0) {
      return true;
    } else {
      showToast({ msg: "数值必须大于0" })
    }
  },
  checkEmptyArray: function (val, msg) {
    if (val.length === 0) {
      showToast({ msg });
    }
    return val.length === 0 ? false : true;
  },
  checkPlatformId: function (list) {
    let result = list.every(item => item.platform ? true : false);
    if (!result) {
      showToast({ msg: "请选择平台" });
      return result
    }
    result = list.every(item => item.platformId ? true : false);
    if (!result) {
      showToast({ msg: "平台id不能为空" });
      return result;
    }
    return true;
  }
}

class validator {
  constructor() {
    this.cache = [];
  }
  add(method, val, msg) {
    this.cache.push(function () {
      return strategies[method](val, msg);
    });
  }
  check() {
    for (let i = 0; i < this.cache.length; i++) {
      const result = this.cache[i]();
      if (!result) {
        return false;
      }
    }
    return true;
  }
}

module.exports = validator